import React, { useState, useEffect } from 'react';
import type { ColumnsType } from 'antd/es/table';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { useKey } from '@/hooks/index';
import { RedoOutlined } from '@ant-design/icons';
import {
  Button,
  Layout,
  Card,
  Divider,
  Popover,
  Table,
  Badge,
  Popconfirm,
  Modal,
  Input,
  message,
} from 'antd';
import CommentSearch from './components/CommentSearch';
import Footers from '@/components/Footer';
import { connect } from 'umi'
import { changeComment, delComments, postComments } from '@/api/comment'
function IndexPage(props: any) {
  const { Header, Footer, Content } = Layout;
  const [pageInfo, setPage] = useState({ page: 1, pageSize: 12 })
  const { setComment, total, dispatch } = props;
  const { TextArea } = Input;
  const [value, setValue] = useState('');
  const [arr, setArr]: any = useState({});
  // const [pass,setPass]=useState('')
  //获取用户信息
  const any: any = localStorage.getItem('user')
  const user = JSON.parse(any)
  useEffect(() => {
    dispatch({
      type: 'comment/INIT',
      pageInfo,
    })
  }, []);
  setComment ? useKey(setComment) : null;
  //刷新内容
  const Refresh = () => {
    dispatch({
      type: 'comment/INIT',
      pageInfo,
    })
  };
  //分页
  const onchanges = (page: number, pageSize: number) => {
    dispatch({
      type: 'comment/INIT',
      pageInfo: {
        page,
        pageSize,
      },
    })
  }
  // 修改评论状态
  const changeCommentStatus = (id: string, pass: boolean) => {
    changeComment(id, pass)
    dispatch({
      type: 'comment/INIT',
      pageInfo,
    });
  };
  //删除评论
  const delComment = (id: string) => {
    delComments(id).then((res: any) => {
      if (res.statusCode === 200) {
        dispatch({
          type: 'comment/INIT',
          pageInfo,
        });
        message.success('删除成功');
      }
    })
  };
  //回复评论弹出框
  const reply = (item: any) => {
    setIsModalOpen(true);
    setValue('')
    setArr(item)
  }
  const [isModalOpen, setIsModalOpen] = useState(false);
  //确认回复
  const handleOk = () => {
    postComments({
      name: user.name,
      email: user.email,
      content: value,
      createByAdmin: true,
      hostId: user.id,
      url: '/details/' + user.id,
      parentCommentId: arr.id,
      replyUserName: arr.name,
      replyUserEmail: arr.email,
    }).then(res => {
      dispatch({
        type: 'comment/INIT',
        pageInfo,
      });
    })
    setIsModalOpen(false);
  };
  const change = (e: any) => {
    setValue(e)
  }
  const handleCancel = () => {
    setIsModalOpen(false);
  };
  interface DataType {
    key: React.Key;
    name: string;
    age: number;
    address: string;
  }
  const columns: ColumnsType<DataType> = [
    {
      title: '状态',
      width: 100,
      dataIndex: 'pass',
      key: 'name',
      fixed: 'left',
      render: (col: string) => {
        return col ? (
          <span>
            <Badge status="success" /> 通过
          </span>
        ) : (
          <span>
            <Badge status="warning" /> 未通过
          </span>
        );
      },
    },
    { title: '称呼', width: 100, dataIndex: 'name', key: 'age' },
    { title: '联系方式', dataIndex: 'email', key: '1', width: 240 },
    {
      title: '原始内容',
      dataIndex: 'content',
      key: '2',
      render: (col: any) => {
        return (
          <Popover
            content={
              <div>
                <p>{col}</p>
              </div>
            }
            title="评论详情-原始内容"
            trigger="hover"
          >
            <span style={{ color: '#0188fb', cursor: 'pointer' }}>
              查看内容
            </span>
          </Popover>
        );
      },
    },
    {
      title: 'HTML内容',
      dataIndex: 'content',
      key: '3',
      width: 100,
      render: (col: any) => {
        return (
          <Popover
            content={<div dangerouslySetInnerHTML={{ __html: col }}></div>}
            title="评论详情-HTML内容"
            trigger="hover"
          >
            <span style={{ color: '#0188fb', cursor: 'pointer' }}>
              查看内容
            </span>
          </Popover>
        );
      },
    },
    {
      title: '管理文章',
      dataIndex: 'url',
      key: '4',
      render: (col: any) => {
        return (
          <Popover
            content={col}
            title="页面预览"
            trigger="hover"
            placement="rightTop"
          >
            <span style={{ color: '#0188fb', cursor: 'pointer' }}>文章</span>
          </Popover>
        );
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createAt',
      key: '5',
      width: 240,
      render: (col: any) => {
        return new Date(col).toLocaleString(); //时间转换
      },
    },
    {
      title: '父级评论',
      dataIndex: 'parentCommentId',
      key: '6',
      render: (col: string) => {
        return col === null ? <span>无</span> : <span>已通过</span>;
      },
    },
    {
      title: '操作',
      key: '7',
      fixed: 'right',
      width: 220,
      render: (item: any) => (
        <div>
          <a onClick={() => {
            changeCommentStatus(item.id, true)
          }}>通过</a>
          <Divider type="vertical" />
          <a onClick={() => {
            changeCommentStatus(item.id, false)
          }}>拒绝</a>
          <Divider type="vertical" />
          <a onClick={() => reply(item)}>回复</a>

          <Divider type="vertical" />
          <Popconfirm
            title="你确定要删除吗?"
            onConfirm={() => {
              delComment(item.id);
            }}
            style={{ width: '400% !important' }}
            okText="确定"
            cancelText="取消"
          >
            <a>删除</a>
          </Popconfirm>
        </div>
      ),
    },
  ];
  //选中显示按钮
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    setSelectedRowKeys(newSelectedRowKeys);
  };
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };
  const hasSelected = selectedRowKeys.length > 0;
  // 多选删除
  const alldel = (arr: any) => {
    arr.forEach((item: any) => {
      delComments(item).then((res: any) => {
        if (res.statusCode === 200) {
          dispatch({
            type: 'comment/INIT',
            pageInfo,
          });
          message.success('删除成功');
        }
      })
    })
  }
  // 多选通过
  const alladopt = (arr: any) => {
    arr.forEach((id: any,pass:any) => {
      changeComment(id, pass)
      console.log(id, pass);
      
    })
  }
  return (
    <Layout>
      <PageHeaderWrapper />
      <Header
        style={{
          background: '#f0f2f5',
          height: '220px',
          padding: '20px 20px 0px 20px',
        }}
      >
        <Card bodyStyle={{ padding: '0px' }}>
          <CommentSearch></CommentSearch>
        </Card>
      </Header>
      <Content style={{ padding: '0px 20px 20px 20px' }}>
        {/* 多选显示按钮 */}
        <Card
          title={
            <span style={{ marginLeft: 8 }}>
              {hasSelected ? (
                <div style={{ height: '20px', width: '300px' }}>
                  <Button style={{ marginLeft: '10px' }} onClick={() => alladopt(selectedRowKeys)}>通过</Button>
                  <Button style={{ marginLeft: '10px' }}>拒绝</Button>
                  <Button danger style={{ marginLeft: '10px' }} onClick={() => alldel(selectedRowKeys)}>
                    删除
                  </Button>
                </div>
              ) : (
                <div style={{ height: '20px' }}></div>
              )}
            </span>
          }
          extra={
            <RedoOutlined
              style={{ cursor: 'pointer', fontSize: '20px' }}
              onClick={() => Refresh()}
            />
          }
        >
          <Table
            pagination={{
              // 总数量
              total,
              // 默认的每条页数
              defaultPageSize: 12,
              // 指定每页可以显示多少条
              pageSizeOptions: [8, 12, 24, 36],
              // 用于显示数据总量和当前数据顺序
              showTotal: (total) => {
                return <>共{total}条</>
              },
              onChange: onchanges,
              // 是否展示 pageSize 切换器，当 total 大于 50 时默认为 true
              showSizeChanger: true
            }}
            rowSelection={rowSelection}
            columns={columns}
            dataSource={setComment}
            scroll={{ x: 1300 }}
          />
        </Card>
      </Content>
      <Footer>
        <Footers></Footers>
      </Footer>
      {/* 回复 */}
      <Modal title="回复评论"
        open={isModalOpen} onOk={() => handleOk()}
        okText={'回复'}
        onCancel={handleCancel}>
        <TextArea
          value={value}
          onChange={(e) => change(e.target.value)}
          placeholder="支持 Markdown"
          autoSize={{ minRows: 6, maxRows: 5 }}
        />
      </Modal>

    </Layout>

  );
}
// connect接收两个参数
// 1. 函数 mapStateToProps
const mapStateToProps = (state: any) => {
  const { comment } = state
  return comment
}
export default connect(mapStateToProps)(IndexPage)
